package com.blakebarrett.components
{
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.ui.Keyboard;
	import flash.utils.Timer;
	
	import mx.controls.Button;
	import mx.events.FlexEvent;
	
	[Event("buttonStillDown")]
	
	[Style(name="buttonRepeatRate", type="Number", inherit="no")]
	
	public class AdvancedButton extends Button
	{
		public function AdvancedButton()
		{
			super();
			autoRepeat = true;
			addEventListeners();
		}
		/*
		override protected function keyDownHandler(event:KeyboardEvent):void
	    {
	        if (!enabled)
	            return;
	
	        if (event.keyCode == Keyboard.SPACE || event.keyCode == Keyboard.ENTER)
	            buttonPressed();
	    }
		*/
		private var _eventToDispatch : String = MouseEvent.CLICK;
		
		private function addEventListeners():void{
			addEventListener(FlexEvent.CREATION_COMPLETE, onCreationComplete );
			addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown );
			addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown );
			addEventListener(MouseEvent.MOUSE_UP, onMouseUp );
			addEventListener(MouseEvent.MOUSE_OUT, onMouseOut );
		}
		
		private function onCreationComplete( e : FlexEvent ) : void {
			// Sets up the timer to repeat keyRepeatRate times per second
			_timer = new Timer( _buttonRepeatRate / 1000 );
			_timer.addEventListener(TimerEvent.TIMER, onTimer );
		}
		
		private function onKeyDown ( e : KeyboardEvent ) : void {
			if ( _enterAsClick && e.keyCode == Keyboard.ENTER ){
				dispatchButtonEvents();
				startTimer();
			}
		}
		
		private function onMouseDown ( e : MouseEvent) : void {
			startTimer();
		}
		
		private function onMouseUp ( e : MouseEvent ) : void {
			stopTimer();
		}
		
		private function onMouseOut ( e : MouseEvent ) : void {
			stopTimer();
		}
		
		private var _timer : Timer;
		
		private function onTimer ( e : TimerEvent ) : void {
			dispatchEvent( new MouseEvent(MouseEvent.MOUSE_DOWN) );
		}
		
		private var _buttonRepeatRate : Number = 10;
		
		private function startTimer () : void {
			_timer.delay = _buttonRepeatRate / 1000;
			_timer.start();
		}
		
		private function stopTimer () : void {
			if ( _timer.running ){
				_timer.stop();
				_timer.reset();
			}
		}
		
		private function dispatchButtonEvents () : void {
			dispatchEvent( new Event('buttonStillDown', true, false ) );
			dispatchEvent(new Event(_eventToDispatch) );
		}
		
		
		private var _enterAsClick : Boolean = true;
		
		[Inspectable(category="General", enumeration="true,false", defaultValue="true")]
		
		public function set enterAsClick ( val : Boolean ) : void {
			_enterAsClick = val;
		}
		
		public function get enterAsClick () : Boolean {
			return _enterAsClick;
		}
	}
}